
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:simple_music_app/components/common/search_song_item.dart';
import 'package:simple_music_app/core/constants/constant.dart';
import 'package:simple_music_app/core/models/play_list.dart';
import 'package:simple_music_app/pages/player_page/models/song_info.dart';
import 'package:simple_music_app/pages/player_page/components/music_control.dart';
import 'package:simple_music_app/core/music_service.dart';
import 'package:simple_music_app/main.dart';

import '../../../core/utils/logger.dart';

class SearchResultPage extends StatefulWidget {
  final String keyword;
  final MusicController audioController = Get.find();

  SearchResultPage({super.key, required this.keyword});

  @override
  State<SearchResultPage> createState() => _SearchResultPageState();
}

class _SearchResultPageState extends State<SearchResultPage> {
  final ScrollController _scrollController = ScrollController();
  List<SongInfo> _songs = [];
  int _offset = 0;
  bool _isLoading = false;
  bool _hasMore = true;

  @override
  void initState() {
    super.initState();
    _loadInitialData();
    _scrollController.addListener(() {
      if (_scrollController.hasClients) {
        final maxScroll = _scrollController.position.maxScrollExtent;
        final currentScroll = _scrollController.position.pixels;
        AppLogger.d(
            '滚动位置: $currentScroll/$maxScroll, 加载中: $_isLoading, 还有更多: $_hasMore');
        // 当滚动到距离底部100像素时预加载
        if (maxScroll - currentScroll <= 100 && !_isLoading && _hasMore) {
          AppLogger.d('触发加载更多数据');
          _loadMoreData();
        }
      }
    });
  }

  List<SongInfo> _allSongs = []; // 缓存所有搜索结果
  static const int _pageSize = 20; // 每页显示数量

  Future<void> _loadInitialData() async {
    setState(() {
      _isLoading = true;
      _allSongs = []; // 清空缓存
    });
    try {
      final results = await searchSongs(widget.keyword);
      if (results.isNotEmpty) {
        widget.audioController.updatePlayList(results
            .map((song) => PlayList(
                songId: "${widget.keyword}|${song.id}",
                songName: song.title,
                artist: song.singer,
                coverUrl: song.cover,
                musicUrl: ""))
            .toList());
      }
      setState(() {
        _allSongs = results;
        _songs = results.take(_pageSize).toList(); // 第一页数据
        _offset = 1;
        _isLoading = false;
        // 总是假设还有更多数据，因为API可能返回更多
        _hasMore = results.isNotEmpty;
        AppLogger.d('初始加载完成，总数据量: ${results.length}, 是否有更多: $_hasMore');
      });
    } catch (e) {
      setState(() {
        _isLoading = false;
      });
      _showErrorDialog(e.toString());
    }
  }

  void _showErrorDialog(String error) {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        backgroundColor: Colors.grey[900],
        title: const Text('搜索异常', style: TextStyle(color: Colors.white)),
        content: Text(error, style: const TextStyle(color: Colors.white)),
        actions: <Widget>[
          TextButton(
            child: const Text('返回', style: TextStyle(color: Colors.white)),
            onPressed: () {
              // 先关闭当前弹窗
              Navigator.pop(context);
              // 然后替换当前路由为首页
              Navigator.pushReplacement(
                context,
                MaterialPageRoute(builder: (context) => const MyHomePage()),
              );
            },
          ),
          TextButton(
            child: const Text('重试', style: TextStyle(color: Colors.blue)),
            onPressed: () {
              Navigator.pop(context);
              _retryWithTimeout();
            },
          ),
        ],
      ),
    );
  }

  Future<void> _retryWithTimeout() async {
    const timeoutDuration = Duration(seconds: 20);
    final stopwatch = Stopwatch()..start();
    bool success = false;

    while (stopwatch.elapsed < timeoutDuration && !success) {
      try {
        setState(() => _isLoading = true);
        final results = await searchSongs(widget.keyword, page: 1)
            .timeout(const Duration(seconds: 5));

        setState(() {
          _songs = results.isNotEmpty ? results : [];
          _offset = 2;
          _isLoading = false;
          _hasMore = results.isNotEmpty;
          success = true;
        });
        return;
      } catch (e) {
        setState(() => _isLoading = false);
        await Future.delayed(const Duration(seconds: 1));
      }
    }

    if (!success) {
      _showErrorDialog('重试超时，请检查网络后重试');
    }
  }

  Future<void> _loadMoreData() async {
    if (_isLoading || !_hasMore) return;

    setState(() {
      _isLoading = true;
    });

    try {
      // 模拟网络延迟
      await Future.delayed(const Duration(milliseconds: 300));

      final nextPage = _offset + 1;
      final start = (nextPage - 1) * _pageSize;
      final end = start + _pageSize;

      if (_allSongs.isNotEmpty && start < _allSongs.length) {
        setState(() {
          _songs.addAll(_allSongs.sublist(
              start, end > _allSongs.length ? _allSongs.length : end));
          _offset = nextPage;
          _hasMore = _songs.length < _allSongs.length;
          AppLogger.d(
              '加载更多数据: 页码=$nextPage, 开始=$start, 结束=$end, 总数=${_allSongs.length}');
        });
      }
    } catch (e) {
      _showErrorDialog(e.toString());
    } finally {
      setState(() {
        _isLoading = false;
      });
    }
  }

  @override
  void dispose() {
    _scrollController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.black,
      appBar: AppBar(
        title: const Text('搜索结果', style: TextStyle(color: Colors.white)),
        backgroundColor: Colors.black,
      ),
      body: Container(
        color: Colors.black,
        child: Column(
          children: [
            Expanded(
              child: ListView.builder(
                controller: _scrollController,
                padding: const EdgeInsets.all(10),
                itemCount: _songs.length + (_hasMore ? 1 : 0),
                itemBuilder: (context, index) {
                  if (index >= _songs.length) {
                    return _buildLoadingIndicator();
                  }
                  final song = _songs[index];
                  return SearchSongItem(
                    title: song.title,
                    artist: song.singer,
                    cover: song.cover,
                    onTap: () => _handlePlaySong(index),
                  );
                },
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildLoadingIndicator() {
    return Padding(
      padding: const EdgeInsets.all(8.0),
      child: Center(
        child: _isLoading
            ? const CircularProgressIndicator()
            : _songs.isEmpty
                ? const Text('没有找到相关歌曲', style: TextStyle(color: Colors.white))
                : const Text('已经到底了', style: TextStyle(color: Colors.white)),
      ),
    );
  }

  void _handlePlaySong(int index) async {
    final song = _songs[index];
    try {
      // 构建符合API要求的songId格式："搜索关键词|歌曲序号"
      final songId = "${widget.keyword}|${song.id}";
      AppLogger.d(
          '点击播放，将请求API: ${MusicAppConstants.musicAppNetUrl}?msg=${widget.keyword}&n=${song.id}&type=json');

      // 使用MusicController的统一播放方法
      await widget.audioController.play(
        index,
        songId,
      );

      // 显示成功提示
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          const SnackBar(
            content: Text('开始播放'),
            duration: Duration(seconds: 1),
          ),
        );
      }
    } catch (e) {
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content: Text('播放失败: ${e.toString().replaceAll('\n', ' ')}'),
            duration: const Duration(seconds: 2),
          ),
        );
      }
    }
  }
}



